package com.mall.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.mall.common.constants.AliPayConstants;
import com.mall.common.resp.ResponseResult;
import com.mall.common.utils.Security;
import com.mall.controller.vo.OrderCategoryXse;
import com.mall.controller.vo.OrderVO;
import com.mall.entity.Cart;
import com.mall.entity.Order;
import com.mall.service.CartService;
import com.mall.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author xyl
 * @date 2021-03-04 18:52
 */
@Api(tags = "订单接口")
@RestController
@RequestMapping("order")
public class OrderController {


    @Autowired
    private OrderService orderService;
    @Autowired
    private CartService cartService;

    @ApiOperation("在购物车中 , 进行提交付款")
    @PostMapping("/cart/toPay")
    public Object cartToPay(@RequestBody List<Cart> carts) {
        if (ObjectUtils.isEmpty(carts)) {
            return ResponseResult.error("不得为空");
        }
        return orderService.cartToPay(carts);
    }

    @ApiOperation("在订单中待付款 ,进行付款 ")
    @PostMapping("/toPay")
    public Object orderToPay(@RequestBody List<Order> orders){
        if (ObjectUtils.isEmpty(orders)) {
            return ResponseResult.error("不得为空");
        }
        return orderService.orderToPay(orders);
    }

    @ApiOperation("支付异步通知,成功后删除购物车信息,并修改订单支付状态")
    @PostMapping("notify")
    public void notify(HttpServletRequest request) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> maps = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name =  iter.next();
            String[] values =  requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"),"utf-8");
            maps.put(name, valueStr);
        }
        orderService.notifyOrder(maps.get("out_trade_no"));
        boolean signVerified = AlipaySignature.rsaCheckV1(maps, AliPayConstants.alipay_public_key, "UTF-8", "RSA2");
        if (!signVerified) {
            return;
        }
    }

    @ApiOperation("当前用户所有订单")
    @GetMapping("list")
    public List<OrderVO> list(Order order){
        order.setCreateBy(Security.getCurrentUserId());
        return orderService.listVO(order);
    }

    @ApiOperation("获取所有订单")
    @PreAuthorize("hasRole('ADMIN') or hasRole('COMMON_ADMIN')")
    @GetMapping("/list/all")
    public List<OrderVO> listAll(Order order){
        return orderService.listVO(order);
    }

    @ApiOperation("提交订单")
    @PostMapping("add")
    public ResponseResult add(@RequestBody List<Cart> carts){
        Order order = new Order();
        String bh = UUID.randomUUID().toString().replaceAll("-", "");
        for (Cart cart : carts) {
            order.setCount(cart.getCount());
            order.setCreateBy(cart.getCreateBy());
            order.setCreateTime(new Date());
            order.setPrice(cart.getPrice());
            order.setGoodsId(cart.getGoodsId());
            order.setTotal(cart.getTotal());
            //创建订单 , 待付款
            order.setOrderStatus(0);
            order.setOrderNumber(bh);
            int count1 = orderService.add(order);
            int count2 = cartService.remove(cart.getCartId());
        }
        return ResponseResult.success(bh);
    }

    @ApiOperation("修改订单状态 , 拼接参数")
    @PostMapping("modify")
    public ResponseResult modify(@RequestParam Integer orderStatus,@RequestParam String orderNumber){
        return ResponseResult.toResponse(orderService.modifyStatusByOrderNumber(orderNumber,orderStatus));
    }


    @ApiOperation("管理员,  获取今日销售额 和 订单数   , 获取总的销售额 和 订单数")
    @GetMapping("/get/today")
    @PreAuthorize("hasRole('ADMIN') or hasRole('COMMON_ADMIN')")
    public ResponseResult getToday(){
        return ResponseResult.success(orderService.getViewInfo());
    }

//
    @ApiOperation("管理员,  根据分类获取销售额 ")
    @GetMapping("/get/category/xse")
    @PreAuthorize("hasRole('ADMIN') or hasRole('COMMON_ADMIN')")
    public Map<String, Float> getViewInfo(){
        return orderService.getOrderCategoryXse();
    }
}
